package protocol

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"iot-base/common/cache"
	"iot-base/devc/common/digest"
	"net/http"
	"time"
)

/*
{
"jsonrpc":"2.0",
"method":"doRTSPPush",
"param":
	{"srcurl":"",
	"pushurl":""}
}
*/

func sendHTTP(method string, body interface{}, uri string, username string, password string) ([]byte, error) {
	fmt.Println("-------------run eachdev---sendHTTP------------", uri, username, password)
	t := digest.NewTransport(username, password)
	var reader *bytes.Reader = nil
	if body != nil {
		bbody, _ := json.Marshal(body)
		if bbody != nil {
			reader = bytes.NewReader(bbody)
		}

	}

	fmt.Println("-------", method, uri, reader)
	var req *http.Request
	var err error
	if reader == nil {
		req, err = http.NewRequest(method, uri, nil)
	} else {
		req, err = http.NewRequest(method, uri, reader)
	}

	if err != nil {
		fmt.Println("-------------send error------------", err)
		return nil, err
	}
	resp, err := t.RoundTrip(req)
	if err != nil {
		fmt.Println("-------------send error---2---------", err)
		return nil, err
	}
	defer resp.Body.Close()
	return ioutil.ReadAll(resp.Body)
	//return body, err
}

//EachDev 遍历设备的回调函数
func EachDev(id string, thing *cache.ThingInfo, dev interface{}, round int64) (interface{}, error) {
	fmt.Println("-------------run eachdev---------------")
	ip := thing.GetThingParam("ip", "127.0.0.1")
	pport := thing.GetThingParam("httpPort", "10080")
	pwd := thing.GetThingParam("password", "admin")
	un := thing.GetThingParam("username", "admin") //thing.Params[""]
	fmt.Println("-------------run eachdev---------------", ip, pport, pwd, un)
	//sip := pip.(string)
	//sport := pport.(string)
	//un := pusername.(string)
	//pwd := ppwd.(string)
	hbAddr := "http://" + ip + ":" + pport + "/manage/heartbeat"
	resp, err := sendHTTP("GET", nil, hbAddr, un, pwd)
	if err != nil {
		fmt.Println("error------------", ip, pport, pwd, un, err)
		return nil, err
	}
	var res map[string]interface{}
	json.Unmarshal(resp, &res)
	if len(res) > 0 {
		ok := res["result"]
		if ok != nil {
			rok := ok.(string)
			if rok == "success" {
				fmt.Println("sucess------------", ip, pport, pwd, un)
				cache.SetLastAliveTime(id, time.Now().Unix())
				return nil, nil
			}
		}
	}
	fmt.Println("error------------------no data return", ip, pport, pwd, un, err)
	return nil, errors.New("error from mm")

}
